#coding=utf-8
import cookielib
import urllib
import urllib2
import re
import string
#设置超时时间
urllib2.socket.setdefaulttimeout(2)

from application.utilities.BeautifulSoup import BeautifulSoup
import config


class ZF():
	def __init__(self,is_liren):
		#判断用户
		self.check_liren = int( is_liren )

		self.cookies = cookielib.LWPCookieJar()
		self.opener = urllib2.build_opener(urllib2.HTTPCookieProcessor(self.cookies))
		urllib2.install_opener(self.opener)
		urllib2.socket.setdefaulttimeout(20)		
		self.base_url    = self.get_base_url()
		self.login_url   = self.base_url + config.login_aspx
		self.code_url    = self.base_url + 'CheckCode.aspx'
		self.target_host = self.base_url[7:22]
		
		#里仁学生或者里仁教师认证
		if( self.check_liren == 1 ):
			self.target_host = self.base_url[7:20]
			self.base_url    = self.base_url[0:20] + '/'
			self.login_url   = self.base_url + config.login_aspx
			self.code_url    = self.base_url + 'CheckCode.aspx'
		self.headers = {
				'Referer':self.base_url + config.login_aspx,
				'Host':self.target_host,
				'User-Agent':"Mozilla/5.0 (X11; Ubuntu; Linux i686;\
						rv:18.0) Gecko/20100101 Firefox/18.0",
				'Connection':'Keep-Alive'
				}
		self.xh = ""
		self.pw = ""
		self.verify_code = ""
		self.VIEWSTATE = ""
		self.pic_path = ""
		self.time_md5 = ""
		self.is_login = 0

	def get_base_url(self):
		# 0:大院  1:里仁  -1:大院教师   2;里仁教师
		try:
			if( self.check_liren == 1 ):
				target = urllib2.urlopen(config.liren_url)
			else:
				target = urllib2.urlopen(config.zf_url)
		except:
			return ""
		with_random_url = target.geturl()
		base_url = with_random_url
		return base_url
	
	def set_login_info(self,xh,pw,verify_code = None):
		self.xh = xh
		self.pw = pw
		if verify_code:
			self.verify_code = verify_code

	def pre(self):
		if self.base_url == "":
			return {'errcode':1,'errmsg':"base_url连接超时！"}
		'''
		初始化登陆,
		获取viewstate参数
		创建验证码图片,放置在/static/verity_cide/中, 并且返回验证码图片名
		'''
		#get __VIEWSTATE
		#return {'errcode':57,'errmsg':self.headers}
		try:
			req = urllib2.Request(self.login_url,headers=self.headers)
			ret = self.opener.open(req)
			page = ret.read()
		except:
			return {'errcode':1,'errmsg':"login_url连接超时！"}

		com = re.compile(r'name="__VIEWSTATE" value="(.*?)"')
		all = com.findall(page)
		try:
			self.VIEWSTATE =  all[0]
		except:
			return {'errcode':1,'errmsg':"接口错误！"}
		#生成key
		import time
		import md5
		self.time_md5 = md5.md5(str(time.time())+self.VIEWSTATE).hexdigest()

		#获取验证码
		content_for_find = page.decode("gbk").encode("utf-8")
		if content_for_find.find('验证码') != -1:
			# get CheckCode.aspx
			try:
				req = urllib2.Request(self.code_url,headers = self.headers)
				a = self.opener.open(req).read()
			except:
				return {'errcode':1,'errmsg':"CheckCode.aspx连接超时！"}
			pic_name = self.time_md5 + ".gif"
			import os
			import sys
			path = os.path.abspath(os.path.dirname(sys.argv[0]))
			self.pic_path = '/static/verify_code/' + pic_name
			filename = path+self.pic_path
			fi = file(filename,'wb')
			fi.write(a)
			fi.close()
		return {'time_md5':self.time_md5,'pic_path':self.pic_path}

	def login(self):
		#return {'errcode':1,'errmsg':self.base_url}
		if self.base_url == "":
			return {'errcode':1,'errmsg':"base_url连接超时！"}

		if self.VIEWSTATE == "":
			pre_ret = self.pre()
			if self.pic_path != "":
				return pre_ret
		#return {'errcode':55,'errmsg':pre_ret}
		if self.pic_path != "":
			verify_code	 = self.verify_code.decode("utf-8").encode("gb2312")
			data = {
				'Button1':'',
				'RadioButtonList1':"学生",
				#"TextBox1":self.xh,
				'txtUserName':self.xh,
				'TextBox2':self.pw,
				#'TextBox3':verify_code	,
				'txtSecretCode':verify_code	,
				'__VIEWSTATE':self.VIEWSTATE,
				'lbLanguage':'',
			}
		else:
			#里仁学生
			if( self.check_liren == 1 ):
				data = {
					'tname':"",
					'tbtns':"",
					'txtXm':"",
					'tnameXw':"yhdl",
					'tbtns':"yhdl|xwxsdl",
					'rblJs':"学生",
					'btnDl':"登 录",
					'txtYhm':self.xh,
					'txtMm':self.pw,
					'__VIEWSTATE':self.VIEWSTATE,	
				}
			#里仁老师
			elif self.check_liren == 2 :
				data = {
					'tname':"",
					'tbtns':"",
					'txtXm':"",
					'tnameXw':"yhdl",
					'tbtns':"yhdl|xwxsdl",
					'rblJs':"教师",
					'btnDl':"登 录",
					'txtYhm':self.xh,
					'txtMm':self.pw,
					'__VIEWSTATE':self.VIEWSTATE,	
				}
			#大院老师
			elif self.check_liren == -1 :
				data = {
					'rblJs':"教师",
					'btnDl':"登 录",
					'txtYhm':self.xh,
					'txtMm':self.pw,
					'__VIEWSTATE':self.VIEWSTATE,
				}
			#大院学生
			else:
				data = {
					'rblJs':"学生",
					'btnDl':"登 录",
					'txtYhm':self.xh,
					'txtMm':self.pw,
					'__VIEWSTATE':self.VIEWSTATE,
				}
		#return {'errcode':1,'errmsg':self.login_url,'base':self.base_url,'header':self.headers,'data':urllib.urlencode(data)}	
		#post_data = urllib.urlencode(data)
		#return {'errcode':1,'login_url':post_data,'check_liren':self.check_liren}
		try:
			post_data = urllib.urlencode(data)
			req = urllib2.Request(url=self.login_url,data=post_data,headers=self.headers)
			ret = self.opener.open(req).read().decode("gbk").encode("utf-8")
		except:
			
			return {'errcode':1,'errmsg':"login_url提交超时！"}		
		
		#return {'errcode':1,'errmsg':ret}		
		
		if ret.find('欢迎您') != -1:
			self.is_login = 1
			return {'errcode':0,'errmsg':'登陆成功！','time_md5':self.time_md5}
		elif ret.find('用户名不存在') != -1:
			return {'errcode':3,'errmsg':"用户名不存在!"}
		elif ret.find('密码错误') != -1:
			return {'errcode':3,'errmsg':"密码错误!"}
		elif ret.find('验证码不正确') != -1:
			return {'errcode':4,'errmsg':"验证码不正确!"}
		elif ret.find('需修改后才能登陆') != -1:
			return {'errcode':6,'errmsg':"密码过弱，请到教务系统修改密码后登陆!"}
		else:
			return {'errcode':7,'errmsg':"未知错误!"}

	def get_html(self, search_item,data={}):
		if self.base_url == "":
			return {'errcode':1,'errmsg':"base_url连接超时！"}
		'''
		仅用来抓取目的网页
		'''
		if self.is_login == 0:
			return {'errcode':8,'errmsg':"未登录！"}

		post_data = urllib.urlencode(data)
		url = self.base_url + search_item + ".aspx?xh=" + self.xh
		try:
			req = urllib2.Request(url = url,data=post_data, headers = self.headers)
			target_html = self.opener.open(req).read().decode('gbk').encode("utf-8")
			if target_html.find('未评价') != -1:
				return {'errcode':10,'errmsg':"有教师未评价！"}

			if target_html.find('还没有进行本学期的教学质量评价') != -1:
				return {'errcode':11,'errmsg':"有课程未评价！"}

			return {'content':target_html}

		except:
			return {'errcode':1,'errmsg':"get_html连接超时！"}			

	def get_cbase_info(self):
		if self.base_url == "":
			return {'errcode':1,'errmsg':"base_url连接超时！"}
		'''
		个人姓名
		'''
		html_pre = self.get_html("xs_main")
		return html_pre

	def get_cinfo(self):
		if self.base_url == "":
			return {'errcode':1,'errmsg':"base_url连接超时！"}
		'''
		个人信息
		'''

		try:
			req = urllib2.Request(self.base_url + "xsgrxx.aspx?xh=" + self.xh,headers = self.headers)
			a = self.opener.open(req).read()
		except:
			return {'errcode':1,'errmsg':"base_url.aspx连接超时！"}
		
		target_html = a.decode('gbk').encode("utf-8")
		if target_html.find('未评价') != -1:
			return {'errcode':10,'errmsg':"有教师未评价！"}

		if target_html.find('还没有进行本学期的教学质量评价') != -1:
			return {'errcode':11,'errmsg':"有课程未评价！"}

		html_name = self.xh + ".html"
		import os
		import sys
		path = os.path.abspath(os.path.dirname(sys.argv[0]))
		self.html_path = '/static/info/' + html_name
		filename = path+self.html_path
		fi = file(filename,'wb')
		fi.write(a)
		fi.close()

		return {'content':target_html}

	def get_cphoto(self):
		if self.base_url == "":
			return {'errcode':1,'errmsg':"base_url连接超时！"}
		'''
		照片
		'''
		try:
			req = urllib2.Request(self.base_url + "readimagexs.aspx?xh=" + self.xh,headers = self.headers)
			a = self.opener.open(req).read()
		except:
			return {'errcode':1,'errmsg':"readimagexs.aspx连接超时！"}

		pic_name = self.xh + ".gif"
		import os
		import sys
		path = os.path.abspath(os.path.dirname(sys.argv[0]))
		self.pic_path = '/static/photo/' + pic_name
		filename = path+self.pic_path
		fi = file(filename,'wb')
		fi.write(a)
		fi.close()
		return self.pic_path

	def get_ctable(self):
		if self.base_url == "":
			return {'errcode':1,'errmsg':"base_url连接超时！"}
		'''
		课表
		'''
		html_pre = self.get_html("xskbcx")
		return html_pre

	def get_cexam(self):
		if self.base_url == "":
			return {'errcode':1,'errmsg':"base_url连接超时！"}
		'''
		考试
		'''
		html_pre = self.get_html("xskscx")
		return html_pre

	def get_cscore(self):
		if self.base_url == "":
			return {'errcode':1,'errmsg':"base_url连接超时！"}
		'''
		成绩
		'''
		if( self.check_liren == 1 ):
			page = self.get_html("xscjcx")
			com = re.compile(r'name="__VIEWSTATE" value="(.*?)"')
			viewstate = com.findall(page['content'])
			data = {
				'hidLanguage':'',
				'ddlXN':'',
				'ddlXQ':'',
				'ddl_kcxz':'',
				'btn_zcj':'1',
				'__VIEWSTATE':viewstate[0],
				'__EVENTTARGET':'',
				'__EVENTARGUMENT':'',
			}
			html_pre = self.get_html("xscjcx",data)
		else:
			page = self.get_html("xscj_gc")
			com = re.compile(r'name="__VIEWSTATE" value="(.*?)"')
			viewstate = com.findall(page['content'])
			data = {
				'ddlXN':'',
				'ddlXQ':'',
				'Button2':'1',
				'__VIEWSTATE':viewstate[0],
			}
			html_pre = self.get_html("xscj_gc",data)
		return html_pre